﻿using ApplicationBase.Core.Domain;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ApplicationBase.Core.Extensions
{
    public static class MediatorExtension
    {
        public static async Task DispatchDomainEventsAsync(this IMediator mediator, DbContext context)
        {
            var domainEntities = context.ChangeTracker.Entries<Entity>()
                .Where(it => it.Entity.DomainEvents != null && it.Entity.DomainEvents.Any());

            #pragma warning disable CS8603 
            var domainEvents = domainEntities
                .SelectMany(it => it.Entity.DomainEvents)
                .ToList();
            #pragma warning restore CS8603

            domainEntities.ToList()
                .ForEach(entity => entity.Entity.ClearDomainEvents());

            foreach (var domainEvent in domainEvents)
                await mediator.Publish(domainEvent);
        }
    }
}
